package com.haizhi.crm.sys.auth.service.impl;

import com.haizhi.crm.common.constant.SysStatus;
import com.haizhi.crm.common.exception.UnexpectedStatusException;
import com.haizhi.crm.common.log.GLog;
import com.haizhi.crm.common.log.LogFactory;
import com.haizhi.crm.common.model.Response;
import com.haizhi.crm.common.util.Md5SaltUtils;
import com.haizhi.crm.sys.auth.dao.DepartmentDao;
import com.haizhi.crm.sys.auth.model.DepartmentDo;
import com.haizhi.crm.sys.auth.model.DepartmentQo;
import com.haizhi.crm.sys.auth.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by yangyijun on 2018/5/30.
 */
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {

    private static final GLog LOG = LogFactory.getLogger(DepartmentServiceImpl.class);

    @Autowired
    private DepartmentDao departmentDao;

    @Override
    public Response save(DepartmentQo departmentQo) {
        try {
            String signature = departmentQo.getSignature();
            departmentQo.setSignature(null);
            String localSignature = Md5SaltUtils.getEncrypted(departmentQo.toString());
            if (localSignature.equals(signature)) {
                DepartmentDo departmentDo = new DepartmentDo();
                departmentDo.setId(departmentQo.getId());
                departmentDo.setName(departmentQo.getName());
                departmentDo.setAllSuperiorDept(departmentQo.getAllSuperiorDept());
                departmentDo.setDirectSuperiorDept(departmentQo.getDirectSuperiorDept());
                departmentDo.setType(departmentQo.getType());
                departmentDo.setEnabledFlag(departmentQo.getEnabledFlag());
                DepartmentDo d = departmentDao.findOne(departmentQo.getId());
                if (null == d) {
                    departmentDo.setCreatedDt(new Date());
                }
                departmentDo.setBank(departmentQo.getBank());
                departmentDo.setCode(departmentQo.getCode());
                departmentDo.setUpdatedDt(new Date());
                departmentDo.setInstitutionId(departmentQo.getInstitutionId());
                departmentDo.setManagerId(departmentQo.getManagerId());
                departmentDo.setParent(departmentQo.getParent());
                departmentDao.save(departmentDo);
                return Response.success();
            } else {
                throw new UnexpectedStatusException(SysStatus.SYNC_DEPARTMENT_ERROR);
            }
        } catch (Exception e) {
            LOG.error("sync department info error", e);
            throw new UnexpectedStatusException(SysStatus.SYNC_DEPARTMENT_ERROR, e);
        }
    }
}
